package cn.qhfn.dao.impl;

import cn.qhfn.dao.BaseDao;
import cn.qhfn.dao.PetDao;
import cn.qhfn.entity.Pet;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class PetDaoImpl extends BaseDao implements PetDao {
    @Override
    public int addPet(Pet pet) {
        String sql = "insert into pet(name,species,age) values(?,?,?)";
        Object[] prs = {pet.getName(),pet.getSpecies(),pet.getAge()};
        return executeUpdate(sql, prs);
    }

    @Override
    public int deletePet(int id) {
        String sql = "delete from pet where id = ?";
        Object[] prs = {id};
        return executeUpdate(sql,prs);
    }

    @Override
    public int updatePet(Pet pet) {
        String sql = "update pet set name=?,species=?,age=? where id = ?";
        Object[] prs = {pet.getName(),pet.getSpecies(),pet.getAge(),pet.getId()};
        return executeUpdate(sql,prs);
    }

    @Override
    public Pet getPet(int id) {
        Pet pet = null;
        String sql = "select id,name,species,age from pet where id = ?";
        Object[] prs = {id};
        ResultSet rs = executeQuery(sql,prs);
        try {
            while (rs.next()) {
                pet = new Pet();
                pet.setId(rs.getInt("id"));
                pet.setName(rs.getString("name"));
                pet.setSpecies(rs.getString("species"));
                pet.setAge(rs.getInt("age"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return pet;
    }

    @Override
    public List<Pet> getPets() {
        List<Pet> pets = new ArrayList<Pet>();
        Pet pet = null;
        String sql = "select id,name,species,age from pet";
        ResultSet rs = executeQuery(sql);
        try {
            while (rs.next()) {
                pet = new Pet();
                pet.setId(rs.getInt("id"));
                pet.setName(rs.getString("name"));
                pet.setSpecies(rs.getString("species"));
                pet.setAge(rs.getInt("age"));
                pets.add(pet);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return pets;
    }
}
